package me.smileface.nio.chat;


import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOChatClient {
    private InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8080);
    private Selector selector;
    private SocketChannel socketChannel;

    private String nickName = "";
    private Charset charset = StandardCharsets.UTF_8;

    public static void main(String[] args) throws IOException {
        new NIOChatClient().session();
    }


    public NIOChatClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open(serverAddress);
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);

        System.out.println("客户端已启动");
    }

    private void session() {
        new ReaderThread().start();
        new WriterThread().start();
    }

    private class ReaderThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) {
                    int select = selector.select();
                    if (select == 0) continue;

                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        process(key);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void process(SelectionKey key) throws IOException {
            if (!key.isValid()) return;

            if (key.isReadable()) {
                SocketChannel channel = (SocketChannel) key.channel();

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                StringBuilder content = new StringBuilder();
                while (channel.read(buffer) > 0) {
                    buffer.flip();
                    content.append(charset.decode(buffer));
                }
                String msg = content.toString();

                if (ChatConst.USER_EXISTS.equals(msg)) {
                    nickName = "";
                }

                System.out.println(msg);
                key.interestOps(SelectionKey.OP_READ);
            }
        }

    }

    private class WriterThread extends Thread {
        @Override
        public void run() {
            try {
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    if (StringUtils.isNotEmpty(line)) {
                        if ("".equals(nickName)) {
                            nickName = line;
                            line = nickName + ChatConst.USER_CONTENT_SPLIT;
                        } else {
                            line = nickName + ChatConst.USER_CONTENT_SPLIT + line;
                        }
                        socketChannel.write(charset.encode(line));
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
